const smsService = require('../common/sms');
const user = module.exports;


// 登录-手机号快速登录
user.loginTel = async (mobile, code) => {
    if (!_.trim(mobile) || !_.trim(code)) throw new Error('手机号或验证码不能为空');

    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let ret = await smsService.check(mobile, code);
    if (!ret) throw new Error('验证码验证失败');

    let userInfo = await helper.getRow(db().md_user, {mobile: mobile}, null, {exclude: ['password', 'wx_id', 'qq_id']});
    if (!userInfo) {
        userInfo = await db().md_user.create({
            id: helper.uuid(),
            mobile: mobile,
            name: '',
            nickname: mobile,
            avatar: '',
            password: helper.uuid(),
        })
    }

    if (userInfo.is_enable === 1) throw new Error('该账号已被禁用');

    smsService.destroy(mobile, code).then().catch();
    return userInfo;
};

// 登录-关联第三方账号
user.loginThird = async (mobile, code, ext = {}) => {
    if (!_.trim(mobile) || !_.trim(code)) throw new Error('手机号或验证码不能为空');

    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let ret = await smsService.check(mobile, code);
    if (!ret) throw new Error('验证码验证失败');

    let userInfo = await helper.getRow(db().md_user, {mobile: mobile}, null, {exclude: ['password', 'wx_id', 'qq_id']});

    if (!userInfo) {
        userInfo = await db().md_user.create({
            id: helper.uuid(),
            mobile: mobile,
            name: '',
            nickname: ext.nickname,
            avatar: ext.headimgurl,
            sex: parseInt(ext.sex) + 1,
            wx_id: ext.userType == 'wx' ? ext.openid : '',
            qq_id: ext.userType == 'qq' ? ext.openid : '',
            password: helper.uuid(),
        })
    } else {
        await db().md_user.update({
            nickname: ext.nickname,
            avatar: ext.headimgurl,
            sex: parseInt(ext.sex) + 1,
            wx_id: ext.userType == 'wx' ? ext.openid : '',
            qq_id: ext.userType == 'qq' ? ext.openid : '',
        }, {where: {id: userInfo.id}});

        if (userInfo.is_enable === 1) throw new Error('该账号已被禁用');

        userInfo = {...userInfo, nickname: ext.nickname, avatar: ext.headimgurl, sex: parseInt(ext.sex) + 1,}
    }

    smsService.destroy(mobile, code).then().catch();
    return userInfo;
};

// 检查手机号
user.checkMobile = async (mobile) => {
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');
    let count = await db().md_user.count({where: {mobile: mobile}});
    if (count) throw new Error('手机号已注册');
    return true;
};

// 登录-手机号密码登录
user.loginPassword = async (mobile, password) => {
    if (!_.trim(mobile) || !_.trim(password)) throw new Error('手机号或密码不能为空');
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let userInfo = await helper.getRow(db().md_user, {
        mobile: mobile,
        password: helper.md5(helper.md5(password))
    }, null, {exclude: ['password', 'wx_id', 'qq_id']});

    if (!userInfo) throw new Error('用户名或者密码错误');

    if (userInfo.is_enable === 1) throw new Error('该账号已被禁用');

    return userInfo;
};

// 注册
user.register = async (mobile, code, password, password_confirm,) => {
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let ret = await smsService.check(mobile, code);
    if (!ret) throw new Error('验证码验证失败');

    if (password !== password_confirm) throw new Error('两次输入的密码不一致');

    let count = await db().md_user.count({where: {mobile: mobile}});
    if (count) throw new Error('手机号已注册');

    let userData = {
        id: helper.uuid(),
        mobile: mobile,
        password: helper.md5(helper.md5(password)),
    };

    let couponData = {
        id: helper.uuid(),
        type: 'FIRST_REGISTER',
        name: '新用户专享优惠券',
        price: 100,
        user_id: userData.id,
    };

    smsService.destroy(mobile, code).then().catch();

    // 注册成功 送优惠券
    return await db().sequelize.transaction(async (t) => {
        await db().md_user.create(userData, {transaction: t});
        await db().md_coupon.create(couponData, {transaction: t})
    });

};

// 修改用户信息
user.saveUser = async (data) => {
    if (!data.id) throw new Error('参数错误');

    if (data.email && !helper.isEmail(data.email)) {
        throw new Error('邮箱格式不正确');
    }

    let id = data.id;
    delete data['id'];

    // 校验用户
    let user = await db().md_user.findOne({where: {nickname: data.nickname}});
    user = helper.parse(user);

    if (user && !!data.nickname && user.id !== id) {
        throw new Error('用户名已存在');
    }

    return await (db().md_user.update(data, {
        where: {
            id: id
        }
    }));
};

// 找回密码
user.forgetPassword = async (mobile, code, password, password_confirm) => {
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let ret = await smsService.check(mobile, code);
    if (!ret) throw new Error('验证码验证失败');

    if (password !== password_confirm) throw new Error('两次输入的密码不一致');

    let count = await db().md_user.count({where: {mobile: mobile}});
    if (!count) throw new Error('用户不存在');

    smsService.destroy(mobile, code).then().catch();

    return await db().md_user.update({
        password: helper.md5(helper.md5(password)),
    }, {where: {mobile: mobile}})
};

// 添加收藏
user.addToFavorite = async (user_id, fav_brand_id) => {
    if (!user_id || !fav_brand_id) throw new Error('参数错误');

    let favArr = fav_brand_id.split('|');

    return await db().sequelize.transaction(async (t) => {
        for (let i = 0; i < favArr.length; i++) {
            let count = await db().md_user_favorite.count({where: {user_id: user_id, fav_brand_id: favArr[i]}});
            if (count <= 0) {
                await db().md_user_favorite.create({
                    id: helper.uuid(),
                    user_id: user_id,
                    fav_brand_id: favArr[i]
                }, {transaction: t});
            }
        }
    });
};

// 取消收藏
user.deleteFavorite = async (user_id, fav_brand_id) => {
    if (!user_id || !fav_brand_id) throw new Error('参数错误');
    let args = {user_id, fav_brand_id};
    return await db().md_user_favorite.destory({where: args});
};

// 获取我的收藏列表
user.favoriteList = async (page = 1, limit = 100, args = {}) => {
    let where = {};
    let order = [
        ['create_time', 'desc']
    ];

    if (args.user_id) {
        where.user_id = args.user_id;
    }

    return await helper.getList(db().md_user_favorite, where, page, limit, order, [
        {
            modal: db().md_brand,
            foreignKey: 'fav_brand_id',
            targetKey: 'id',
            as: 'brand_info',
            relation: 'one',
            include: [
                {
                    modal: db().md_brand_class,
                    foreignKey: 'category',
                    targetKey: 'code',
                    as: 'category_info',
                    relation: 'one',
                }
            ]
        }
    ]);
};

// 获取优惠卷列表
user.couponList = async (page = 1, limit = 100, args = {}) => {
    let where = {};
    let order = [
        ['create_time', 'desc']
    ];

    if (args.user_id) {
        where.user_id = args.user_id;
    }

    if (args.is_used) {
        where.is_used = args.is_used;
    }

    return await helper.getList(db().md_coupon, where, page, limit, order);
};

// 用户统计
user.stat = async (user_id) => {
    return {
        myCoupon: await db().md_coupon.count({where: {is_used: 1, user_id: user_id}}),
        myFav: await db().md_user_favorite.count({where: {user_id: user_id}}),
        myOrder: await db().md_order.count({where: {buyer_id: user_id}}),
        price: await db().md_order.sum('total_price', {
            where: {
                buyer_id: user_id,
                status: {$in: [2, 3, 4]}
            }
        }),
        loginCount: await db().md_user_login_log.count({where: {user_id: user_id}})

    }
};

// 导航列表
user.userList = async (page = 1, limit = 100, args = {}) => {
    let where = {};
    let order = [['create_time', 'desc']];

    if (args.keyword) {
        where['$or'] = {
            name: {$like: `%${args.keyword}%`},
            nickname: {$like: `%${args.keyword}%`},
            mobile: {$like: `%${args.keyword}%`}
        };
    }

    let listRet = await helper.getList(db().md_user, where, page, limit, order);

    for (let i = 0; i < listRet.rows.length; i++) {
        listRet.rows[i].price = await db().md_order.sum('total_price', {
            where: {
                buyer_id: listRet.rows[i].id,
                status: {$in: [2, 3, 4]}
            }
        })
    }

    return listRet;
};

// 随机取三个
user.randomUser = async (args = {}) => {
    let limit = args.limit || 3;

    return await db().admin_user.findAll({
        limit: limit,
        order: [
            [db().Sequelize.literal('RAND()')]
        ],
        where: {
            is_enable: 1,
            type: 1,
        }
    })
};






